package notify

import (
	"errors"
	"go-iot/app/models"
	"go-iot/app/common/mysql"
	"gorm.io/gorm"
	"time"
)

// 分页查询通知
func PageNotify(page *models.PageQuery, createId *int64) (*models.PageResult[models.Notify], error) {
	var notify []models.Notify
	var total int64
	
	query := mysql.DB.Model(&models.Notify{})
	
	// 添加条件过滤
	for _, condition := range page.Condition {
		query = query.Where(condition)
	}
	
	// 添加创建者过滤
	if createId != nil {
		query = query.Where("create_id = ?", *createId)
	}
	
	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}
	
	// 执行分页查询
	if err := query.Order("create_time desc, id desc").
		Offset(page.PageOffset()).
		Limit(page.PageSize).
		Find(&notify).Error; err != nil {
		return nil, err
	}
	
	result := models.PageUtil(total, page.PageNum, page.PageSize, notify)
	return &result, nil
}

func ListAll(ob *models.Notify, createId *int64) ([]models.Notify, error) {
	var notify []models.Notify
	query := mysql.DB.Model(&models.Notify{})
	
	if len(ob.Name) > 0 {
		query = query.Where("name LIKE ?", "%"+ob.Name+"%")
	}
	if len(ob.Type) > 0 {
		query = query.Where("type = ?", ob.Type)
	}
	if len(ob.State) > 0 {
		query = query.Where("state = ?", ob.State)
	}
	if createId != nil {
		query = query.Where("create_id = ?", *createId)
	}
	
	if err := query.Find(&notify).Error; err != nil {
		return nil, err
	}
	
	return notify, nil
}

func AddNotify(ob *models.Notify) error {
	ob.State = models.Stopped
	ob.CreateTime = time.Now()
	return mysql.DB.Create(ob).Error
}

func UpdateNotify(ob *models.Notify) error {
	return mysql.DB.Model(ob).
		Select("name", "config", "template", "type", "desc").
		Updates(ob).Error
}

func UpdateNotifyState(ob *models.Notify) error {
	if ob.Id == 0 {
		return errors.New("id must be present")
	}
	
	return mysql.DB.Model(ob).Update("state", ob.State).Error
}

func DeleteNotify(ob *models.Notify) error {
	return mysql.DB.Delete(ob).Error
}

func GetNotify(id int64) (*models.Notify, error) {
	var notify models.Notify
	
	result := mysql.DB.First(&notify, id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, result.Error
	}
	
	return &notify, nil
}

func GetNotifyMust(id int64) (*models.Notify, error) {
	p, err := GetNotify(id)
	if err != nil {
		return nil, err
	}
	if p == nil {
		return nil, errors.New("notify not exist")
	}
	return p, nil
}
